package com.sjz.ctkj.canvasstudy;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sjz.ctkj.canvasstudy.internetmanage.ReqestUrl;
import com.sjz.ctkj.canvasstudy.utils.ShareUtils;
import com.sjz.ctkj.canvasstudy.utils.SysUtils;
import com.sjz.ctkj.canvasstudy.utils.SystemUtil;
import com.sjz.ctkj.canvasstudy.utils.ToastUtils;
import com.sjz.ctkj.canvasstudy.utils.UpdateAppHttpUtil;
import com.sjz.ctkj.canvasstudy.utils.ZipUtils;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import okhttp3.Call;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private WebView mWebView;
    private ProgressBar progress_wheel;
    String url="http://res.ky-express.com/h5/video/72.html";
//    String url="http://soft.imtt.qq.com/browser/tes/feedback.html";
    String requestUrl=ReqestUrl.DOWNLOAD_ZIP_URL;
    private TextView isnotintenert_tv,download_progrees,download_btn,download_btn2;
    private boolean isSHowImei=false;
    String imei="";
    private ShareUtils shareUtils;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        shareUtils = new ShareUtils(this);
        hideBottomUIMenu();//隐藏虚拟按键
        registBrocatRciver();
        imei=SystemUtil.ID();
        // 调用 Handler 来异步设置别名
        if(!"1".equals(shareUtils.getTag())){
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, imei));
            addJpshTag(imei);
        }

        isnotintenert_tv=(TextView)this.findViewById(R.id.isnotintenert_tv);
        isnotintenert_tv.setOnClickListener(this);
        isnotintenert_tv.setText(imei);
        download_progrees=(TextView)this.findViewById(R.id.download_progrees);
        download_progrees.setVisibility(View.GONE);

        download_btn=(TextView)this.findViewById(R.id.download_btn);
        download_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downloadFile("https://tomcat.xzcysoft.com/zjj/adscreen.zip");
            }
        });
        download_btn2=(TextView)this.findViewById(R.id.download_btn2);
        download_btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downloadFile("https://tomcat.xzcysoft.com/zjj/zipFiles/20190903/201909031248129549107/adscreen.zip");
            }
        });
        loadWebview();
    }


    public static boolean isRoot() {
        return new File("/system/bin/su").exists() || new File("/system/xbin/su").exists();
    }
    public class MyWebClient extends WebViewClient {

        @Override
        public void onPageFinished(com.tencent.smtt.sdk.WebView webView, String s) {
            super.onPageFinished(webView, s);
            progress_wheel.setVisibility(View.GONE);
//            mWebView.loadUrl("javascript:(function() { var videos = document.getElementsByTagName('video'); for(var i=0;i<videos.length;i++){videos[i].play();}})()");
            webView.loadUrl("javascript:myFunction()");
        }

        @Override
        public void onPageStarted(com.tencent.smtt.sdk.WebView webView, String s, Bitmap bitmap) {
            super.onPageStarted(webView, s, bitmap);
            progress_wheel.setVisibility(View.VISIBLE);
        }
    }
    //版本升级
    public void updateVersion(){
        new UpdateAppManager
                .Builder()
                //当前Activity
                .setActivity(this)
                //实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil())
                .dismissNotificationProgress()
                //更新地址
                .setUpdateUrl(ReqestUrl.UPDATEVERSION_URL)
                .setThemeColor(ContextCompat.getColor(this,R.color.tvcolor_13))
                .build()
//                .checkNewApp(new SilenceUpdateCallback());
//                //检测是否有新版本
                .checkNewApp(new UpdateCallback(){
                    @Override
                    protected void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                        String myVersionName = SysUtils.getVersionName(MainActivity.this);
                        if(!myVersionName.equals(updateApp.getNewVersion())){
                            updateAppManager.showDialogFragment();
                        }
                    }

                    @Override
                    protected void noNewApp(String error) {
                        super.noNewApp(error);
                    }

                });

    }
   public Handler myHandler = new Handler(){
       @Override
       public void handleMessage(Message msg) {
           super.handleMessage(msg);
           switch (msg.what){
               case 100:
                   reshHtmlUrl();//刷新url
                   break;
               case 200://解压文件
                   new Thread(new Runnable() {
                       @Override
                       public void run() {
                           try {
                               if("1".equals(shareUtils.getDeleteUp())){//如果html路径不是空就解压到第2个文件夹
                                   ZipUtils.UnZipFolder(savePath+"/"+fileName,unZipPath2,myHandler);
                               }else{//如果html路径是空就解压到第1个文件夹
                                   ZipUtils.UnZipFolder(savePath+"/"+fileName,unZipPath,myHandler);
                               }
                           } catch (Exception e) {
                               e.printStackTrace();
                           }

                       }
                   }).start();
                   break;
               case 300:
                   download_progrees.setVisibility(View.VISIBLE);
                   download_progrees.setText("解压："+msg.obj+"%");
                   break;
           }
       }
   };
    public void reshHtmlUrl(){

        isnotintenert_tv.setBackgroundColor(getResources().getColor(R.color.transfle));
        isnotintenert_tv.setGravity(Gravity.RIGHT);
        isnotintenert_tv.setText("");
        String showUlr="";
        if("1".equals(shareUtils.getDeleteUp())){//如果html路径不是空就解压到第2个文件夹
            shareUtils.setDeleteUp("0");
            showUlr= unZipPath2+"/adscreen/start.html";
        }else {//如果html路径是空就解压到第1个文件夹
            shareUtils.setDeleteUp("1");
            showUlr = unZipPath + "/adscreen/start.html";
        }
        File file = new File(showUlr);
        if(file.exists()){
            download_progrees.setVisibility(View.GONE);
            ToastUtils.popUpToast("解压成功");
            mWebView.loadUrl("file://sdcard/"+showUlr);
            shareUtils.setHtmlUrl("file://sdcard/"+showUlr);
        }

        File delefile = new File(savePath+"/"+fileName);
        if(delefile.exists()){
            Utils.deleteDir(delefile);
        }
        if("1".equals(shareUtils.getDeleteUp())){//如果是1删除unziopath2
            File delefile2 = new File(unZipPath2);
            if(delefile2.exists()){
                Utils.deleteAllDir(unZipPath2);
            }
        }else{
            File delefile3 = new File(unZipPath);
            if(delefile3.exists()){
                Utils.deleteAllDir(unZipPath);
            }
        }

    }

    public void cleanWebview(){
        mWebView.clearCache(true);
        mWebView.destroy();
    }

    private void loadWebview()
    {
//        mWebView=(com.tencent.smtt.sdk.WebView)this.findViewById(R.id.wv_contnet);
        mWebView=(WebView) this.findViewById(R.id.wv_contnet);
        mWebView.loadUrl("file:///android_asset/start.html");
        progress_wheel=(ProgressBar)this.findViewById(R.id.progress_wheel);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setPluginsEnabled(true);
        mWebView.getSettings().setPluginState(com.tencent.smtt.sdk.WebSettings.PluginState.ON);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);// 支持js
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);
        mWebView.getSettings().setAllowFileAccessFromFileURLs(true);
        mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

//        mWebView.setWebViewClient(new WebViewClient());//防止加载网页时调起系统浏览器
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(new MyWebClient());//防止加载网页时调起系统浏览器
//        if(shareUtils.getHtmlUrl()!=null&&!"".equals(shareUtils.getHtmlUrl())){
//            isnotintenert_tv.setBackgroundColor(getResources().getColor(R.color.transfle));
//            isnotintenert_tv.setGravity(Gravity.RIGHT);
//            isnotintenert_tv.setText("");
//            mWebView.loadUrl(shareUtils.getHtmlUrl());
//        }else{
//            isnotintenert_tv.setBackgroundColor(getResources().getColor(R.color.white));
//            isnotintenert_tv.setGravity(Gravity.CENTER);
//        }

    }

    /**
     * 下载附件
     */
//     /mnt/sdcard
    private String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/adscreen/myzip";//下载文件的存储绝对路径
    private String unZipPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/adscreen/usezip";//解压的zip文件路径
    private String unZipPath2 = Environment.getExternalStorageDirectory().getAbsolutePath() + "/adscreen/usezip2";
    String fileName = "adscreen.zip";//文件名称【应该动态获取，此处测试，所以写死即可】
    public void downloadFile(String url){
        ToastUtils.popUpToast("开始下载压缩包" );
        download_progrees.setVisibility(View.VISIBLE);
        OkHttpUtils.get()
                .url(url)
                .tag(this)
                .build()
                .execute(new FileCallBack(savePath,fileName) {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtils.popUpToast("下载zip失败");
                        download_progrees.setVisibility(View.GONE);
                    }
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        download_progrees.setText((int) (100 * progress)+"%");
                    }
                    @Override
                    public void onResponse(File downloadFile, int id) {
                        download_progrees.setVisibility(View.GONE);
                        try {
                            File file = new File(savePath+"/"+fileName);
                            if(file.exists()){
                                ToastUtils.popUpToast("下载成功" );
                                myHandler.sendEmptyMessage(200);
//                                Utils.upZipFile(file, unZipPath,myHandler);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }



    //下载apk
    private String apkPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/adscreen";
    String apkName = "adscreen.apk";//文件名称【应该动态获取，此处测试，所以写死即可】
    public void downloadAPK(String url){
        OkHttpUtils.get()
                .url(url)
                .tag(this)
                .build()
                .execute(new FileCallBack(apkPath,apkName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtils.popUpToast("失败");
                    }
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                    }
                    @Override
                    public void onResponse(File downloadFile, int id) {
                        try {
                            File file = new File(apkPath+"/"+apkName);
                            if(file.exists()){
//                                Utils.upZipFile(file, unZipPath,myHandler);
//                              install(apkPath+"/"+apkName);
                                if( silentInstall(apkPath+"/"+apkName)){
                                    ToastUtils.popUpToast("程序静默安装已成功，不知道自动打开了吗 看下！");
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

//                        File file = new File(unZipPath + "/view/homepage/homepage.html");
//                        if (file.exists()) {
//                            tv_progress.setVisibility(View.GONE);
//                            //显示html网页
//                            webView.loadUrl("file:" + unZipPath + "/view/homepage/homepage.html");
//                        }
                    }
                });
    }
    @Override
    public void onClick(View v) {
       switch (v.getId()){
           case R.id.isnotintenert_tv:
               if(isSHowImei){
                   isnotintenert_tv.setText(imei);
                   isSHowImei=false;
               }else{
                   isSHowImei=true;
                   isnotintenert_tv.setText("");
               }
               break;
       }
    }
    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    shareUtils.setTag("1");
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, imei));
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    break;
            }

        }
    };

    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
//                    Log.d(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
//                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };
    public void addJpshTag(String phone){
        OkHttpUtils
                .post()
                .url(ReqestUrl.ADD_JPUSHTAG_URL)
                .addParams("deviceNo",phone)
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.popUpToast("请求超时");
            }
            @Override
            public void onResponse(String response, int id) {
                if(ReqestUrl.rebacRequestJson(response)!=null){
                }
            }
        });
    }
    public MyBrocatRecicer myBrocatRecicer;
    public void registBrocatRciver(){
        myBrocatRecicer=new MyBrocatRecicer();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ReqestUrl.REQUEST_DOWNLOAD_ZIP);
        filter.addAction(ReqestUrl.REQUEST_DOWNLOAD_VERSION);
        registerReceiver(myBrocatRecicer,filter);
    }
    class MyBrocatRecicer extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(ReqestUrl.REQUEST_DOWNLOAD_ZIP)){
                requestUrl=intent.getStringExtra("value");
                downloadFile(requestUrl);
            }else if(intent.getAction().equals(ReqestUrl.REQUEST_DOWNLOAD_VERSION)){
                updateVersion();
//                if(isRoot()){
//                    downloadAPK("http://tomcat.xzcysoft.com/zjj/adscreen.apk");
//                }else{
//
//                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
        if(myBrocatRecicer!=null){
            unregisterReceiver(myBrocatRecicer);
        }
        cleanWebview();
        System.exit(0);
    }
    public static boolean silentInstall(String apkPath) {
        boolean result = false;
        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        BufferedReader successStream = null;
        Process process = null;
        try {
            // 申请 su 权限
            process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            // 执行 pm install 命令
            String command = "pm install -r " + apkPath + "\n";
            dataOutputStream.write(command.getBytes(Charset.forName("UTF-8")));
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            StringBuilder errorMsg = new StringBuilder();
            String line;
            while ((line = errorStream.readLine()) != null) {
                errorMsg.append(line);
            }
//            log.debug("silent install error message:{}", errorMsg);
            StringBuilder successMsg = new StringBuilder();
            successStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
            // 读取命令执行结果
            while ((line = successStream.readLine()) != null) {
                successMsg.append(line);
            }
//            log.debug("silent install success message:{}", successMsg);
            // 如果执行结果中包含 Failure 字样就认为是操作失败，否则就认为安装成功
            if (!(errorMsg.toString().contains("Failure") || successMsg.toString().contains("Failure"))) {
                result = true;
            }
        } catch (Exception e) {
//            log.error(e);
        } finally {
            try {
                if (process != null) {
                    process.destroy();
                }
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
                if (successStream != null) {
                    successStream.close();
                }
            } catch (Exception e) {
                // ignored
            }
        }
        return result;
    }
    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu(){
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
//                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }


}
